package com.google.code.openperfmon.web;

import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.ng.ExecuteOperations;
import org.apache.struts2.dispatcher.ng.InitOperations;
import org.apache.struts2.dispatcher.ng.PrepareOperations;
import org.apache.struts2.dispatcher.ng.filter.FilterHostConfig;
import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

import com.google.code.openperfmon.db.DBManager;

public class StrutsDispatcherWithCleanup extends StrutsPrepareAndExecuteFilter {
	@Override
    public void init(FilterConfig filterConfig) throws ServletException {
        InitOperations init = new InitOperations();
        try {
            FilterHostConfig config = new FilterHostConfig(filterConfig);
            init.initLogging(config);
            Dispatcher dispatcher = init.initDispatcher(config);
            init.initStaticContentLoader(config, dispatcher);

            prepare = new PrepareAndCleanupOperations(filterConfig.getServletContext(), dispatcher);
            execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);
			this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);

            postInit(dispatcher, filterConfig);
        } finally {
            init.cleanup();
        }

    }
    
    private static class PrepareAndCleanupOperations extends PrepareOperations {

		public PrepareAndCleanupOperations(ServletContext servletContext,
				Dispatcher dispatcher) {
			super(servletContext, dispatcher);
		}
    	
		@Override
		public void cleanupRequest(HttpServletRequest request) {
			DBManager.cleanup();
			super.cleanupRequest(request);
		}
    }
}
